<template>
  <div class="login">
    <div class="login_box">
      <el-form
      ref="loginFormRef"
      label-width="0"
      class="login_form"
      :model="loginForm"
      :rules="loginFormRules">
        <!-- 用户名 -->
        <el-form-item  prop="username">
          <el-input
          prefix-icon="el-icon-user"
          v-model="loginForm.username"></el-input>
        </el-form-item>
        <!-- 密码 -->
        <el-form-item prop="password">
          <el-input
          prefix-icon="el-icon-shopping-bag-2"
          v-model="loginForm.password"
          show-password></el-input>
        </el-form-item>
        <!-- 按钮 -->
        <el-form-item class="btns">
          <el-button type="primary" @click="Login()">登录</el-button>
          <el-button type="info" @click="resetLoginForm()">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script>
import { login } from '@/api/login'
import { Message } from 'element-ui'

export default {
  name: 'Login',
  data() {
    return {
      loginForm: {
        username: 'admin',
        password: '123456'
      },
      // 用户校验
      loginFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 2, max: 10, message: '长度在 2 到 10 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入登录密码', trigger: 'change' },
          { min: 2, max: 10, message: '长度在 6 到 13 个字符', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    // 重置
    resetLoginForm() {
      this.$refs.loginFormRef.resetFields()
    },
    // 登录
    Login() {
      this.$refs.loginFormRef.validate(valid => {
        if (!valid) return
        login(this.loginForm).then(res => {
          console.log(res)
          if (res.meta.status !== 200) return Message.error('登录失败')
          Message.success('登录成功')
          window.sessionStorage.setItem('token', res.data.token)
          this.$router.push('/home')
        })
      })
    }
  }
}
</script>

<style lang="scss" scoped>
  .login {
  background-color: #2b4b6b;
  height: 100%;
  .login_box {
  width: 450px;
  height: 360px;
  background-color: #fff;
  border-radius: 3px;
  position: absolute;
  left: 50%;
  top: 50%;
  -webkit-transform: translate(-50%, -50%);
  background-color: #fff;
  .login_form {
  position: absolute;
  bottom: 60px;
  width: 100%;
  padding: 0 20px;
  box-sizing: border-box;
    }
  .btns {
    display: flex;
    justify-content: center;
    }
  }
}
</style>
